package com.example.demo;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

class WriteHelper {
    public static void sendData(OutputStream outputStream, String data) throws IOException {
        synchronized (WriteHelper.class) {
            byte[] body = null;
            body = data.getBytes(StandardCharsets.UTF_8);
            int length = 4 + body.length;
            ByteBuffer buffer = ByteBuffer.allocate(length);
            buffer.order();
            buffer.putInt(body.length);
            buffer.put(body);
            if (outputStream != null) {
                outputStream.write(buffer.array());
                outputStream.flush();
            }
        }
    }

    public static void sendData(OutputStream outputStream, File file, String type, String config) throws IOException {
        synchronized (WriteHelper.class) {
            long totalLength = 0L;
            try {
                totalLength = 12 + file.length() + type.getBytes("UTF-8").length + config.getBytes("UTF-8").length;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            ByteBuffer buffer = ByteBuffer.allocate(Math.toIntExact(totalLength));
            buffer.order();
            buffer.putInt(Math.toIntExact(file.length()));
            byte[] bytes = new byte[1024];
            int length;
            FileInputStream fis = new FileInputStream(file);
            while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
                buffer.put(bytes, 0, length);
            }
            buffer.putInt(type.getBytes("UTF-8").length);
            buffer.put(type.getBytes("UTF-8"));
            buffer.putInt(config.getBytes("UTF-8").length);
            buffer.put(config.getBytes("UTF-8"));
            if (outputStream != null) {
                outputStream.write(buffer.array());
                outputStream.flush();
            }
        }
    }
}
